﻿namespace WMS6.Web.Billing
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using WMS6.Web;
    using WMS6.Web.BillingServiceRef;

    public class Invoice : BasePage
    {
        protected HtmlInputButton btnAction;
        protected Button btnAddDetail;
        protected Button btnDelete;
        protected Button btnDeleteDetail;
        protected Button btnGoBack;
        protected Button btnNew;
        protected Button btnPayment;
        protected Button btnSave;
        protected CheckBox chkIsAmountSubmit;
        protected CheckBox chkIsInvoiceSubmit;
        protected DropDownList ddlBillingObject;
        protected DropDownList ddlDueFromTo;
        protected DropDownList ddlStatus;
        protected HtmlForm F9211;
        protected GridView gvInvoiceDetail;
        protected GridView gvInvoicePaymentDetail;
        protected HtmlInputHidden hdncalendarFlag;
        protected HtmlInputHidden hdnDataFormat;
        protected HtmlInputHidden hdnFlag;
        protected HtmlInputHidden hdnFrom;
        protected HtmlInputHidden hdnInvoiceID;
        protected HtmlInputHidden hdnLineID;
        protected HtmlInputHidden hdnRowIndex;
        protected HtmlHead Head1;
        protected HtmlImage img1;
        protected Label lblBillingDate;
        protected Label lblBillingObject;
        protected Label lblBillingObjectID;
        protected Label lblDueFromTo;
        protected Label lblInvoiceID;
        protected Label lblMsg;
        protected Label lblOwner;
        protected Label lblRemark;
        protected Label lblStatus;
        protected LinkButton lnkbtnAmountCancle;
        protected LinkButton lnkbtnAmountSubmit;
        protected LinkButton lnkbtnInvoiceCancle;
        protected LinkButton lnkbtnInvoiceSubmit;
        protected HtmlLink mycss;
        protected Label one1;
        protected Label one2;
        protected Label one3;
        protected ScriptManager ScriptManager1;
        protected HtmlTableCell tdlnkbtnAmountCancle;
        protected HtmlTableCell tdlnkbtnAmountSubmit;
        protected HtmlTableCell tdlnkbtnInvoiceCancle;
        protected HtmlTableCell tdlnkbtnInvoiceSubmit;
        protected TextBox txtBillingDate;
        protected TextBox txtBillingObject;
        protected TextBox txtInvoiceID;
        protected TextBox txtRemark;
        protected UpdatePanel up1;

        protected void btnAddDetail_Click(object sender, EventArgs e)
        {
            if (this.hdnFlag.Value != "1")
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_015");
            }
            else
            {
                base.Response.Redirect(string.Format("InvoiceDetail.aspx?from={0}&ID={1}&LineID={2}&BillingObject={3}&BillingObjectID={4}&DueFromTo={5}", new object[] { base.UrlEncode(this.hdnFrom.Value), base.UrlEncode(this.txtInvoiceID.Text.Trim()), base.UrlEncode(this.hdnLineID.Value), base.UrlEncode(this.ddlBillingObject.SelectedValue), base.UrlEncode(this.txtBillingObject.Text.Trim()), base.UrlEncode(this.ddlDueFromTo.SelectedValue) }), true);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.ddlStatus.SelectedValue != "New")
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_014");
            }
            else
            {
                try
                {
                    InvoiceInfo invoiceInfo = base.DataEntityViewState as InvoiceInfo;
                    if (invoiceInfo != null)
                    {
                        if (string.IsNullOrEmpty(BillingServiceClientProxy.GetInstance().DeleteInvoice(invoiceInfo)))
                        {
                            this.lblMsg.Text = base.GetGlobalMsgResource("F9210_011");
                        }
                        else
                        {
                            base.Response.Redirect("Invoice.aspx?from=" + this.hdnFrom.Value, false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_011") + ex.Message;
                }
            }
        }

        protected void btnDeleteDetail_Click(object sender, EventArgs e)
        {
            try
            {
                List<string> selectedID = new List<string>();
                List<string> invoiceID = new List<string>();
                for (int i = 0; i < this.gvInvoiceDetail.Rows.Count; i++)
                {
                    if (((CheckBox) this.gvInvoiceDetail.Rows[i].FindControl("chbSelect")).Checked)
                    {
                        if (this.gvInvoiceDetail.DataKeys[i]["Status"].ToString() != "New")
                        {
                            this.lblMsg.Text = base.GetGlobalMsgResource("F9210_016");
                            return;
                        }
                        invoiceID.Add(this.txtInvoiceID.Text);
                        selectedID.Add(this.gvInvoiceDetail.DataKeys[i]["LineID"].ToString());
                    }
                }
                if ((selectedID == null) || (selectedID.Count == 0))
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_004");
                }
                else if (string.IsNullOrEmpty(BillingServiceClientProxy.GetInstance().DeleteInvoiceDetail(invoiceID, selectedID)))
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_011");
                }
                else
                {
                    this.SetInvoiceInfo2Form();
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_011") + ex.Message;
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", " <script type=\"text/javascript\" >setTab('one',2,3) </script>", false);
            }
        }

        protected void btnGoBack_Click(object sender, EventArgs e)
        {
            switch (this.hdnFrom.Value)
            {
                case "query":
                    base.Response.Redirect("InvoiceQuery.aspx", false);
                    break;

                case "list":
                    base.Response.Redirect("InvoiceList.aspx?from=edit", false);
                    break;
            }
        }

        protected void btnPayment_Click(object sender, EventArgs e)
        {
            try
            {
                List<InvoicePaymentDetailInfo> invoicePaymentDetailListInfo = new List<InvoicePaymentDetailInfo>();
                for (int i = 0; i < this.gvInvoiceDetail.Rows.Count; i++)
                {
                    if (((CheckBox) this.gvInvoiceDetail.Rows[i].FindControl("chbSelect")).Checked)
                    {
                        InvoicePaymentDetailInfo invoicePaymentDetailInfo = new InvoicePaymentDetailInfo {
                            InvoiceID = this.txtInvoiceID.Text.Trim(),
                            LineID = int.Parse(this.gvInvoiceDetail.DataKeys[i]["LineID"].ToString()),
                            CreatedBy = base.UserInfo.UserID,
                            UpdatedBy = base.UserInfo.UserID
                        };
                        decimal tempDec = 0M;
                        if (!string.IsNullOrEmpty(((TextBox) this.gvInvoiceDetail.Rows[i].FindControl("txtCurPayAmount")).Text.Trim()))
                        {
                            if (decimal.TryParse(((TextBox) this.gvInvoiceDetail.Rows[i].FindControl("txtCurPayAmount")).Text.Trim(), out tempDec))
                            {
                                tempDec = decimal.Parse(((TextBox) this.gvInvoiceDetail.Rows[i].FindControl("txtCurPayAmount")).Text.Trim());
                            }
                            else
                            {
                                tempDec = 0M;
                            }
                        }
                        else
                        {
                            tempDec = 0M;
                        }
                        if (tempDec <= 0M)
                        {
                            this.lblMsg.Text = base.GetGlobalMsgResource("F9210_022");
                            return;
                        }
                        decimal payAmount = decimal.Parse(this.gvInvoiceDetail.DataKeys[i]["PayAmount"].ToString()) + tempDec;
                        if (payAmount > decimal.Parse(this.gvInvoiceDetail.DataKeys[i]["InvoiceAmount"].ToString()))
                        {
                            this.lblMsg.Text = string.Format(base.GetGlobalMsgResource("F9210_017"), this.gvInvoiceDetail.DataKeys[i]["LineID"].ToString());
                            return;
                        }
                        if (this.gvInvoiceDetail.DataKeys[i]["Status"].ToString() == "Closed")
                        {
                            this.lblMsg.Text = base.GetGlobalMsgResource("F9210_018");
                            return;
                        }
                        invoicePaymentDetailInfo.PayAmount = decimal.Parse(((TextBox) this.gvInvoiceDetail.Rows[i].FindControl("txtCurPayAmount")).Text.Trim());
                        invoicePaymentDetailListInfo.Add(invoicePaymentDetailInfo);
                    }
                }
                if (invoicePaymentDetailListInfo.Count == 0)
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_004");
                }
                else if (string.IsNullOrEmpty(BillingServiceClientProxy.GetInstance().InsertInvoicePaymentDetail(invoicePaymentDetailListInfo)))
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_010");
                }
                else
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9210_009");
                    this.SetInvoiceInfo2Form();
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_010") + ex.Message;
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", " <script type=\"text/javascript\" >setTab('one',2,3) </script>", false);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtInvoiceID.Text.Trim()))
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_012");
            }
            else if (string.IsNullOrEmpty(this.txtBillingObject.Text.Trim()))
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_013");
            }
            else if (string.IsNullOrEmpty(this.txtBillingDate.Text.Trim()))
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_028");
            }
            else
            {
                DateTime dt = new DateTime();
                if (!DateTime.TryParse(this.txtBillingDate.Text.Trim(), out dt))
                {
                    this.lblMsg.Text = base.GetGlobalMsgResource("F9230_007");
                }
                else
                {
                    this.InsertInvoiceInfo();
                }
            }
        }

        protected void ddlBillingObject_TextChanged(object sender, EventArgs e)
        {
            this.txtBillingObject.Text = "";
        }

        protected void gvInvoiceDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            (sender as GridView).PageIndex = e.NewPageIndex;
            (sender as GridView).DataSource = (base.DataEntityViewState as InvoiceInfo).InvoiceDetailListInfo;
            (sender as GridView).DataBind();
            ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", " <script type=\"text/javascript\" >setTab('one',2,3) </script>", false);
        }

        protected void gvInvoiceDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int i = this.gvInvoiceDetail.PageIndex * this.gvInvoiceDetail.PageSize;
                e.Row.Cells[0].Text = ((e.Row.RowIndex + 1) + i).ToString();
                base.SetGridViewLongTextLabel((Label) e.Row.FindControl("lblRemark"));
                ((TextBox) e.Row.FindControl("txtCurPayAmount")).Attributes.Add("onblur", "setPaymentRowIndex(" + e.Row.RowIndex + ")");
            }
        }

        protected void gvInvoiceDetail_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                string sortDirection = string.Empty;
                if (base.GridViewSortDirection == SortDirection.Ascending)
                {
                    base.GridViewSortDirection = SortDirection.Descending;
                    sortDirection = "DESC";
                }
                else
                {
                    base.GridViewSortDirection = SortDirection.Ascending;
                    sortDirection = "ASC";
                }
                InvoiceInfo invoiceInfo = base.DataEntityViewState as InvoiceInfo;
                DataView dv = CADataConverter.ToDataTable(invoiceInfo.InvoiceDetailListInfo).DefaultView;
                dv.Sort = e.SortExpression + " " + sortDirection;
                base.BindData2GridView(this.gvInvoiceDetail, dv);
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = ex.Message;
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", "<script language='javascript'>setTab('one',2,3);</script>", false);
            }
        }

        protected void gvInvoicePaymentDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            (sender as GridView).PageIndex = e.NewPageIndex;
            (sender as GridView).DataSource = (base.DataEntityViewState as InvoiceInfo).InvoicePaymentDetailListInfo;
            (sender as GridView).DataBind();
            ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", " <script type=\"text/javascript\" >setTab('one',3,3) </script>", false);
        }

        protected void gvInvoicePaymentDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int i = this.gvInvoicePaymentDetail.PageIndex * this.gvInvoicePaymentDetail.PageSize;
                e.Row.Cells[0].Text = ((e.Row.RowIndex + 1) + i).ToString();
            }
        }

        private void InsertInvoiceInfo()
        {
            DateTime dt = DateTime.Now;
            try
            {
                InvoiceInfo InvoiceInfo = new InvoiceInfo {
                    InvoiceID = this.txtInvoiceID.Text.Trim(),
                    DueFromTo = this.ddlDueFromTo.SelectedValue,
                    BillingObject = this.ddlBillingObject.SelectedValue,
                    BillingObjectID = this.txtBillingObject.Text.Trim(),
                    Status = this.ddlStatus.SelectedValue
                };
                if (DateTime.TryParse(this.txtBillingDate.Text.Trim(), out dt))
                {
                    InvoiceInfo.BillingDate = DateTime.Parse(this.txtBillingDate.Text.Trim());
                }
                else
                {
                    InvoiceInfo.BillingDate = new DateTime();
                }
                InvoiceInfo.Remark = this.txtRemark.Text.Trim();
                InvoiceInfo.CreatedBy = base.UserInfo.UserID;
                InvoiceInfo.UpdatedBy = base.UserInfo.UserID;
                InvoiceInfo.WhName = base.UserInfo.WhDbDesc;
                if (this.chkIsAmountSubmit.Checked)
                {
                    InvoiceInfo.IsAmountSubmit = "Y";
                }
                else
                {
                    InvoiceInfo.IsAmountSubmit = "N";
                }
                if (this.chkIsInvoiceSubmit.Checked)
                {
                    InvoiceInfo.IsInvoiceSubmit = "Y";
                }
                else
                {
                    InvoiceInfo.IsInvoiceSubmit = "N";
                }
                string result = string.Empty;
                if (this.hdnFlag.Value != "1")
                {
                    result = BillingServiceClientProxy.GetInstance().InsertInvoice(InvoiceInfo);
                }
                else
                {
                    result = BillingServiceClientProxy.GetInstance().UpdateInvoice(InvoiceInfo);
                }
                if (string.IsNullOrEmpty(result))
                {
                    this.lblMsg.Text = this.txtInvoiceID.Text + base.GetGlobalMsgResource("F9210_010");
                }
                else
                {
                    this.lblMsg.Text = this.txtInvoiceID.Text + base.GetGlobalMsgResource("F9210_009");
                    base.DataEntityViewState = InvoiceInfo;
                    this.SetInvoiceInfo2Form();
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_010") + ex.Message;
            }
        }

        protected void lnkbtnAmountCancle_Click(object sender, EventArgs e)
        {
            string invoiceSubmit = "N";
            string amountSubmit = "N";
            if (this.chkIsInvoiceSubmit.Checked)
            {
                invoiceSubmit = "Y";
            }
            this.UpdateInvoiceSubmit(invoiceSubmit, amountSubmit);
        }

        protected void lnkbtnAmountSubmit_Click(object sender, EventArgs e)
        {
            string invoiceSubmit = "Y";
            string amountSubmit = "Y";
            this.UpdateInvoiceSubmit(invoiceSubmit, amountSubmit);
        }

        protected void lnkbtnInvoiceCancle_Click(object sender, EventArgs e)
        {
            if (this.chkIsAmountSubmit.Checked)
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_026");
            }
            else
            {
                string invoiceSubmit = "N";
                string amountSubmit = "N";
                this.UpdateInvoiceSubmit(invoiceSubmit, amountSubmit);
            }
        }

        protected void lnkbtnInvoiceSubmit_Click(object sender, EventArgs e)
        {
            string invoiceSubmit = "Y";
            string amountSubmit = "N";
            if (this.chkIsAmountSubmit.Checked)
            {
                amountSubmit = "Y";
            }
            this.UpdateInvoiceSubmit(invoiceSubmit, amountSubmit);
        }

        private void LoadData()
        {
            base.BindData2DDLBySysCode(this.ddlStatus, "InvoiceStatus");
            base.BindData2DDLBySysCode(this.ddlBillingObject, "BillingObject");
            base.BindData2DDLBySysCode(this.ddlDueFromTo, "DueFromTo");
            this.txtBillingDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            if (!string.IsNullOrEmpty(base.Request.QueryString["ID"]))
            {
                this.hdnFlag.Value = "1";
                this.txtInvoiceID.Text = base.Request.QueryString["ID"].ToString();
                this.hdnInvoiceID.Value = base.Request.QueryString["ID"].ToString();
                this.SetInvoiceInfo2Form();
            }
            if (!string.IsNullOrEmpty(base.Request.QueryString["from"]))
            {
                this.hdnFrom.Value = base.Request.QueryString["from"].ToString();
            }
            if (!string.IsNullOrEmpty(base.Request.QueryString["detail"]))
            {
                ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", "<script language='javascript'>setTab('one',2,3);</script>", false);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                base.InitPage(this.Page);
                this.LoadData();
            }
        }

        private void SetInvoiceInfo2Form()
        {
            try
            {
                InvoiceInfo InvoiceInfo = BillingServiceClientProxy.GetInstance().GetInvoiceByID(this.txtInvoiceID.Text);
                if (InvoiceInfo != null)
                {
                    this.txtInvoiceID.Text = InvoiceInfo.InvoiceID;
                    this.txtInvoiceID.Enabled = false;
                    this.ddlDueFromTo.SelectedValue = InvoiceInfo.DueFromTo;
                    this.ddlBillingObject.SelectedValue = InvoiceInfo.BillingObject;
                    this.txtBillingObject.Text = InvoiceInfo.BillingObjectID;
                    this.ddlStatus.SelectedValue = InvoiceInfo.Status;
                    this.txtBillingDate.Text = base.GetPreferenceShortDate(InvoiceInfo.BillingDate);
                    this.txtRemark.Text = InvoiceInfo.Remark;
                    this.chkIsInvoiceSubmit.Checked = InvoiceInfo.IsInvoiceSubmit == "Y";
                    this.chkIsAmountSubmit.Checked = InvoiceInfo.IsAmountSubmit == "Y";
                    this.ddlBillingObject.Enabled = false;
                    this.ddlDueFromTo.Enabled = false;
                    this.txtBillingObject.Enabled = false;
                    this.img1.Visible = false;
                    if (InvoiceInfo.Status == "Closed")
                    {
                        this.btnSave.Enabled = false;
                        this.btnDelete.Enabled = false;
                        this.btnAddDetail.Enabled = false;
                        this.btnDeleteDetail.Enabled = false;
                        this.btnPayment.Enabled = false;
                    }
                    if ((InvoiceInfo.InvoiceDetailListInfo != null) && (InvoiceInfo.InvoiceDetailListInfo.Count > 0))
                    {
                        InvoiceInfo.InvoiceDetailListInfo.Sort((Comparison<InvoiceDetailInfo>) ((p1, p2) => Comparer<int>.Default.Compare(p1.LineID, p2.LineID)));
                        this.hdnLineID.Value = (InvoiceInfo.InvoiceDetailListInfo[InvoiceInfo.InvoiceDetailListInfo.Count - 1].LineID + 10).ToString();
                    }
                    else
                    {
                        this.hdnLineID.Value = "10";
                    }
                    this.hdnFlag.Value = "1";
                    if ((InvoiceInfo.InvoiceDetailListInfo != null) && (InvoiceInfo.InvoiceDetailListInfo.Count > 0))
                    {
                        for (int i = 0; i < InvoiceInfo.InvoiceDetailListInfo.Count; i++)
                        {
                            InvoiceInfo.InvoiceDetailListInfo[i].CurPayAmount = InvoiceInfo.InvoiceDetailListInfo[i].InvoiceAmount - InvoiceInfo.InvoiceDetailListInfo[i].PayAmount;
                        }
                    }
                    base.BindData2GridView(this.gvInvoiceDetail, InvoiceInfo.InvoiceDetailListInfo);
                    base.BindData2GridView(this.gvInvoicePaymentDetail, InvoiceInfo.InvoicePaymentDetailListInfo);
                    base.DataEntityViewState = InvoiceInfo;
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = ex.Message;
            }
        }

        protected void txtCurPayAmount_TextChanged(object sender, EventArgs e)
        {
            try
            {
                decimal tempDec = 0M;
                int rowIndex = 0;
                if (!string.IsNullOrEmpty(this.hdnRowIndex.Value))
                {
                    rowIndex = int.Parse(this.hdnRowIndex.Value);
                    string num = ((TextBox) this.gvInvoiceDetail.Rows[rowIndex].FindControl("txtCurPayAmount")).Text.Trim();
                    if (!string.IsNullOrEmpty(num))
                    {
                        if (decimal.TryParse(num, out tempDec))
                        {
                            tempDec = decimal.Parse(num);
                        }
                        else
                        {
                            tempDec = 0M;
                        }
                    }
                }
                if (tempDec <= 0M)
                {
                    ((TextBox) this.gvInvoiceDetail.Rows[rowIndex].FindControl("txtCurPayAmount")).Text = "0";
                }
                else
                {
                    ((TextBox) this.gvInvoiceDetail.Rows[rowIndex].FindControl("txtCurPayAmount")).Text = tempDec.ToString();
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = ex.Message;
            }
            finally
            {
                ScriptManager.RegisterStartupScript(this.Page, base.GetType(), "", "<script language='javascript'>setTab('one',2,3);</script>", false);
            }
        }

        private void UpdateInvoiceSubmit(string invoiceSubmit, string amountSubmit)
        {
            try
            {
                List<InvoiceInfo> invoiceListInfo = new List<InvoiceInfo>();
                InvoiceInfo InvoiceInfo = new InvoiceInfo {
                    InvoiceID = this.txtInvoiceID.Text.Trim(),
                    UpdatedBy = base.UserInfo.UserID,
                    IsInvoiceSubmit = invoiceSubmit,
                    IsAmountSubmit = amountSubmit
                };
                invoiceListInfo.Add(InvoiceInfo);
                if (string.IsNullOrEmpty(BillingServiceClientProxy.GetInstance().UpdateInvoiceSubmit(invoiceListInfo)))
                {
                    this.lblMsg.Text = this.txtInvoiceID.Text + base.GetGlobalMsgResource("F9210_025");
                }
                else
                {
                    this.lblMsg.Text = this.txtInvoiceID.Text + base.GetGlobalMsgResource("F9210_024");
                    base.DataEntityViewState = InvoiceInfo;
                    this.SetInvoiceInfo2Form();
                }
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = base.GetGlobalMsgResource("F9210_025") + ex.Message;
            }
        }
    }
}

